<template>
  <div class="dashboard-container">
    <el-container class="layout-container">
      <!-- Sidebar Navigation -->
      <el-aside width="260px" class="app-sidebar">
        <div class="sidebar-header">
          <div class="logo-icon">
            <el-icon><DataAnalysis /></el-icon>
          </div>
          <span class="app-name">TeamPlan360</span>
        </div>
        
        <el-menu
          :default-active="activeTab"
          class="sidebar-menu"
          @select="handleMenuSelect"
          background-color="transparent"
          text-color="#6b7280"
          active-text-color="#4f46e5"
        >
          <el-menu-item index="overview">
            <el-icon><Odometer /></el-icon>
            <span>工作概览</span>
          </el-menu-item>
          <el-menu-item index="annual">
            <el-icon><Calendar /></el-icon>
            <span>年度计划</span>
          </el-menu-item>
          <el-menu-item index="monthly">
            <el-icon><Files /></el-icon>
            <span>月度计划</span>
          </el-menu-item>
          <el-menu-item index="weekly">
            <el-icon><List /></el-icon>
            <span>周计划</span>
          </el-menu-item>
          <el-menu-item index="weeklyReports">
            <el-icon><Document /></el-icon>
            <span>工作周报</span>
          </el-menu-item>
          <el-menu-item index="monthlyReports">
            <el-icon><Files /></el-icon>
            <span>月度报告</span>
          </el-menu-item>
        </el-menu>
        
        <div class="sidebar-footer">
          <div class="user-profile">
            <el-avatar :size="36" class="user-avatar">{{ user?.username?.charAt(0).toUpperCase() }}</el-avatar>
            <div class="user-info">
              <span class="username">{{ user?.username }}</span>
              <span class="role">员工</span>
            </div>
            <el-button type="text" class="logout-btn" @click="showPasswordDialog = true" title="修改密码">
              <el-icon><Lock /></el-icon>
            </el-button>
            <el-button type="text" class="logout-btn" @click="handleLogout" title="退出登录">
              <el-icon><SwitchButton /></el-icon>
            </el-button>
          </div>
        </div>
      </el-aside>

      <!-- Main Content -->
      <el-container>
        <el-header class="app-header">
          <div class="header-left">
            <h2 class="page-title">{{ getPageTitle(activeTab) }}</h2>
          </div>
          <div class="header-right">
            <!-- AI状态测试按钮 -->
            <el-tooltip 
              :content="aiStatusTooltip" 
              placement="bottom"
            >
              <el-button 
                :type="aiStatusType"
                :loading="testingAI"
                @click="testAIStatus"
                circle
                size="large"
              >
                <el-icon v-if="!testingAI">
                  <component :is="aiStatusIcon" />
                </el-icon>
              </el-button>
            </el-tooltip>
            
            <el-button v-if="activeTab === 'annual'" type="primary" @click="startNewAnnualPlan">
              <el-icon><Plus /></el-icon> 新增年度计划
            </el-button>
          </div>
        </el-header>

        <el-main class="app-main">
          <!-- Guided Workflow (Overlay) -->
          <transition name="fade">
            <div v-if="showGuidedWorkflow" class="workflow-overlay">
              <div class="workflow-container">
                <div class="workflow-header">
                  <div class="header-text">
                    <h2>工作计划设定向导</h2>
                    <p>智能辅助您完成年度与月度计划的制定</p>
                  </div>
                  <el-button circle @click="showGuidedWorkflow = false"><el-icon><Close /></el-icon></el-button>
                </div>
                
                <div class="workflow-steps">
                  <el-steps :active="workflowStep" align-center finish-status="success">
                    <el-step title="年度重点" description="设定核心目标" />
                    <el-step title="月度拆解" description="AI智能拆解" />
                    <el-step title="确认执行" description="生成执行计划" />
                  </el-steps>
                </div>

                <div class="workflow-content">
                  <!-- Step 1: Annual Goal -->
                  <div v-if="workflowStep === 0" class="step-content">
                    <el-form :model="annualPlanForm" :rules="annualRules" ref="annualFormRef" label-position="top">
                      <el-form-item label="年度核心目标" prop="title">
                        <el-input v-model="annualPlanForm.title" placeholder="例如：完成核心产品重构与上线" size="large" />
                      </el-form-item>
                      
                      <el-form-item label="详细描述与愿景" prop="description">
                        <el-input 
                          v-model="annualPlanForm.description" 
                          type="textarea" 
                          :rows="4"
                          placeholder="描述您希望在今年达成的具体成果..."
                        />
                      </el-form-item>
                      
                      <el-row :gutter="20">
                        <el-col :span="12">
                          <el-form-item label="关键量化指标 (KPIs)" prop="objectives">
                            <el-input 
                              v-model="annualPlanForm.objectives" 
                              type="textarea" 
                              :rows="3"
                              placeholder="例如：用户增长50%，性能提升30%..."
                            />
                          </el-form-item>
                        </el-col>
                        <el-col :span="12">
                          <el-form-item label="工作重点策略">
                            <el-input 
                              v-model="annualPlanForm.keyFocus" 
                              type="textarea" 
                              :rows="3"
                              placeholder="实现目标的关键路径和策略..."
                            />
                          </el-form-item>
                        </el-col>
                      </el-row>
                    </el-form>
                    
                    <div class="step-footer">
                      <el-button @click="showGuidedWorkflow = false">取消</el-button>
                      <el-button type="primary" size="large" @click="generateMonthlyPlans" :loading="generatingMonthly">
                        智能生成月度计划 <el-icon class="el-icon--right"><MagicStick /></el-icon>
                      </el-button>
                    </div>
                  </div>

                  <!-- Step 2: Monthly Review -->
                  <div v-if="workflowStep === 1" class="step-content">
                    <div class="monthly-grid-scroll">
                      <div class="monthly-plans-grid">
                        <el-card 
                          v-for="(plan, index) in generatedMonthlyPlans" 
                          :key="index" 
                          class="monthly-preview-card"
                          shadow="hover"
                        >
                          <template #header>
                            <div class="card-header">
                              <span class="month-badge">{{ plan.month }}月</span>
                              <span class="month-title">{{ plan.title }}</span>
                              <el-button type="primary" link @click="editMonthlyPlan(plan, index)">
                                <el-icon><Edit /></el-icon>
                              </el-button>
                            </div>
                          </template>
                          <div class="card-body">
                            <p class="desc">{{ plan.description }}</p>
                            <div class="tags">
                              <el-tag size="small" v-for="(task, i) in plan.tasks.slice(0,2)" :key="i" class="task-tag">
                                {{ task.length > 15 ? task.substring(0,15) + '...' : task }}
                              </el-tag>
                              <el-tag v-if="plan.tasks.length > 2" size="small" type="info">+{{ plan.tasks.length - 2 }}</el-tag>
                            </div>
                          </div>
                        </el-card>
                      </div>
                    </div>
                    
                    <div class="step-footer">
                      <el-button @click="workflowStep = 0">上一步</el-button>
                      <el-button type="primary" size="large" @click="confirmMonthlyPlans" :loading="confirmingMonthly">
                        确认并创建所有计划 <el-icon class="el-icon--right"><Check /></el-icon>
                      </el-button>
                    </div>
                  </div>

                  <!-- Step 3: Success -->
                  <div v-if="workflowStep === 2" class="step-content centered">
                    <el-result icon="success" title="计划创建成功" sub-title="您的年度计划及所有月度计划已生成完毕">
                      <template #extra>
                        <el-button type="primary" @click="handleWorkflowComplete">进入工作台</el-button>
                      </template>
                    </el-result>
                  </div>
                </div>
              </div>
            </div>
          </transition>

          <!-- Tab Content Views -->
          <div v-if="!showGuidedWorkflow" class="content-wrapper">
            
            <!-- Overview Tab -->
            <div v-if="activeTab === 'overview'" class="overview-view">
              <div class="stats-row">
                <el-card shadow="hover" class="stat-card">
                  <div class="stat-icon bg-blue"><el-icon><Calendar /></el-icon></div>
                  <div class="stat-info">
                    <span class="label">年度计划</span>
                    <span class="value">{{ annualPlansCount }}</span>
                  </div>
                </el-card>
                <el-card shadow="hover" class="stat-card">
                  <div class="stat-icon bg-green"><el-icon><Files /></el-icon></div>
                  <div class="stat-info">
                    <span class="label">月度计划</span>
                    <span class="value">{{ monthlyPlansCount }}</span>
                  </div>
                </el-card>
                <el-card shadow="hover" class="stat-card">
                  <div class="stat-icon bg-purple"><el-icon><List /></el-icon></div>
                  <div class="stat-info">
                    <span class="label">周计划</span>
                    <span class="value">{{ weeklyPlansCount }}</span>
                  </div>
                </el-card>
                <el-card shadow="hover" class="stat-card">
                  <div class="stat-icon bg-orange"><el-icon><Warning /></el-icon></div>
                  <div class="stat-info">
                    <span class="label">待办事项</span>
                    <span class="value">{{ pendingReportsCount }}</span>
                  </div>
                </el-card>
              </div>

              <div class="recent-activity">
                <h3><el-icon><Timer /></el-icon> 近期动态</h3>
                <el-empty v-if="!existingAnnualPlans.length" description="暂无计划，请先创建年度计划" />
                <div v-else class="annual-list">
                  <el-card v-for="plan in existingAnnualPlans" :key="plan.id" class="annual-item" shadow="hover">
                    <div class="annual-header">
                      <h4>{{ plan.year }}年度目标：{{ plan.title }}</h4>
                      <el-tag :type="getStatusType(plan.status)">{{ getStatusText(plan.status) }}</el-tag>
                    </div>
                    <p class="annual-desc">{{ plan.description }}</p>
                    <div class="annual-actions">
                      <el-button size="small" @click="viewPlanDetails(plan)">查看详情</el-button>
                      <el-button size="small" type="danger" plain @click="deletePlan(plan)">删除</el-button>
                    </div>
                  </el-card>
                </div>
              </div>
            </div>

            <!-- Other Tabs (Components) -->
            <div v-if="activeTab === 'annual'" class="tab-view">
              <annual-plans @create-plan="startNewAnnualPlan" />
            </div>
            <div v-if="activeTab === 'monthly'" class="tab-view">
              <monthly-plans />
            </div>
            <div v-if="activeTab === 'weekly'" class="tab-view">
              <weekly-plans />
            </div>
            <div v-if="activeTab === 'weeklyReports'" class="tab-view">
              <weekly-reports />
            </div>
            <div v-if="activeTab === 'monthlyReports'" class="tab-view">
              <monthly-reports />
            </div>

          </div>
        </el-main>
      </el-container>
    </el-container>

    <!-- Edit Dialog -->
    <el-dialog v-model="showEditMonthlyDialog" title="编辑月度计划" width="500px" destroy-on-close>
      <el-form :model="editingMonthlyPlan" label-position="top">
        <el-form-item label="月度主题">
          <el-input v-model="editingMonthlyPlan.title" />
        </el-form-item>
        <el-form-item label="关键任务 (每行一个)">
          <el-input v-model="editingMonthlyPlan.tasksText" type="textarea" :rows="6" />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="showEditMonthlyDialog = false">取消</el-button>
        <el-button type="primary" @click="saveMonthlyPlanEdit">保存修改</el-button>
      </template>
    </el-dialog>
    <ChangePasswordDialog v-model="showPasswordDialog" />
  </div>
</template>

<script>
import { ref, computed, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { useAuthStore } from '../stores/auth'
import { ElMessage, ElMessageBox } from 'element-plus'
import AnnualPlans from '../components/AnnualPlans.vue'
import MonthlyPlans from '../components/MonthlyPlans.vue'
import WeeklyPlans from '../components/WeeklyPlans.vue'
import WeeklyReports from '../components/WeeklyReports.vue'
import MonthlyReports from '../components/MonthlyReports.vue'
import AnnualSummary from '../components/AnnualSummary.vue'
import ChangePasswordDialog from '../components/ChangePasswordDialog.vue'

import { 
  Odometer, Calendar, Files, List, Document, SwitchButton, Plus, Refresh, Warning, Lock 
} from '@element-plus/icons-vue'
import axios from 'axios'

export default {
  name: 'EmployeeDashboard',
  components: {
    AnnualPlans, MonthlyPlans, WeeklyPlans, WeeklyReports, MonthlyReports, AnnualSummary, ChangePasswordDialog,
    Odometer, Calendar, Files, List, Document, SwitchButton, Plus, Refresh, Warning, Lock
  },
  setup() {
    const router = useRouter()
    const authStore = useAuthStore()
    
    const activeTab = ref('annual')
    const showPasswordDialog = ref(false)
    const user = computed(() => authStore.user)
    
    // Guided Workflow State
    const hasAnnualPlan = ref(false)
    const showGuidedWorkflow = ref(false)
    const workflowStep = ref(0)
    const generatingMonthly = ref(false)
    const confirmingMonthly = ref(false)
    const showEditMonthlyDialog = ref(false)
    const existingAnnualPlans = ref([])
    const selectedAnnualPlan = ref(null)
    
    // Forms
    const annualPlanForm = ref({
      year: new Date().getFullYear(),
      title: '',
      description: '',
      objectives: '',
      keyFocus: ''
    })
    const annualFormRef = ref()
    const annualRules = {
      title: [{ required: true, message: '请输入年度目标标题', trigger: 'blur' }],
      description: [{ required: true, message: '请输入年度目标详细描述', trigger: 'blur' }],
      objectives: [{ required: true, message: '请输入关键指标', trigger: 'blur' }]
    }
    
    // Generated Data
    const generatedMonthlyPlans = ref([])
    const editingMonthlyPlan = ref({})
    const editingMonthlyIndex = ref(-1)
    
    // Stats
    const annualPlansCount = ref(0)
    const monthlyPlansCount = ref(0)
    const weeklyPlansCount = ref(0)
    const pendingReportsCount = ref(0)
    
    // AI Status
    const testingAI = ref(false)
    const aiStatus = ref(null) // null | 'available' | 'unavailable'
    const aiStatusMessage = ref('点击测试AI服务')
    const aiStatusDetails = ref('')
    
    const aiStatusType = computed(() => {
      switch (aiStatus.value) {
        case 'available': return 'success'
        case 'unavailable': return 'danger'
        default: return 'info'
      }
    })
    
    const aiStatusIcon = computed(() => {
      switch (aiStatus.value) {
        case 'available': return 'CircleCheck'
        case 'unavailable': return 'CircleClose'
        default: return 'Connection'
      }
    })
    
    const aiStatusTooltip = computed(() => {
      if (testingAI.value) return 'AI服务测试中...'
      if (!aiStatus.value) return '点击测试AI服务状态'
      return aiStatusMessage.value + (aiStatusDetails.value ? `\n${aiStatusDetails.value}` : '')
    })
    
    // Methods
    const handleMenuSelect = (index) => {
      activeTab.value = index
    }

    const handleLogout = () => {
      authStore.logout()
      router.push('/login')
    }

    const getPageTitle = (tab) => {
      const titles = {
        overview: '工作概览',
        annual: '年度计划管理',
        monthly: '月度计划管理',
        weekly: '周计划管理',
        weeklyReports: '工作周报',
        monthlyReports: '月度报告'
      }
      return titles[tab] || '工作台'
    }

    const checkAnnualPlan = async () => {
      try {
        const response = await axios.get('/api/plans/annual', {
          headers: { Authorization: `Bearer ${authStore.token}` }
        })
        hasAnnualPlan.value = response.data && response.data.length > 0
        existingAnnualPlans.value = response.data || []
        annualPlansCount.value = response.data.length
      } catch (error) {
        console.error('检查年度计划失败:', error)
      }
    }
    
    const startNewAnnualPlan = () => {
      showGuidedWorkflow.value = true
      workflowStep.value = 0
      selectedAnnualPlan.value = null
      annualPlanForm.value = {
        year: new Date().getFullYear(),
        title: '',
        description: '',
        objectives: '',
        keyFocus: ''
      }
    }

    const generateMonthlyPlans = async () => {
      if (!annualFormRef.value) return
      
      await annualFormRef.value.validate(async (valid) => {
        if (valid) {
          generatingMonthly.value = true
          try {
            const response = await axios.post('/api/ai-suggestions/annual-breakdown', {
              goal: annualPlanForm.value.description,
              keyMetrics: annualPlanForm.value.objectives,
              keyFocus: annualPlanForm.value.keyFocus,
              year: annualPlanForm.value.year
            }, {
              headers: { Authorization: `Bearer ${authStore.token}` }
            })
            
            if (response.data && response.data.monthlyPlans) {
              generatedMonthlyPlans.value = response.data.monthlyPlans.map(plan => {
                const [year, month] = plan.month.split('-').map(Number)
                const taskStrings = plan.tasks ? plan.tasks.map(task => 
                  `${task.title} - ${task.description} (${task.priority}优先级, ${task.estimatedHours}小时)`
                ) : []
                
                return {
                  ...plan,
                  year, month,
                  tasks: taskStrings,
                  tasksText: taskStrings.join('\n'),
                  originalTasks: plan.tasks || [],
                  keyMetrics: plan.keyMetrics ? plan.keyMetrics.join('，') : ''
                }
              })
              workflowStep.value = 1
              ElMessage.success('月度计划生成成功！')
            } else {
              generateDefaultMonthlyPlans()
              workflowStep.value = 1
              ElMessage.info('使用默认模板生成月度计划')
            }
          } catch (error) {
            generateDefaultMonthlyPlans()
            workflowStep.value = 1
            ElMessage.warning('AI服务不可用，已使用默认模板')
          } finally {
            generatingMonthly.value = false
          }
        }
      })
    }

    const generateDefaultMonthlyPlans = () => {
      const currentYear = annualPlanForm.value.year
      const months = ['一月', '二月', '三月', '四月', '五月', '六月', '七月', '八月', '九月', '十月', '十一月', '十二月']
      
      generatedMonthlyPlans.value = months.map((monthName, index) => {
        const month = index + 1
        const allTasks = [`${monthName}重点工作 - 推进年度目标落实 (high优先级, 40小时)`]
        
        return {
          month,
          title: `${monthName}工作计划`,
          description: `基于年度目标"${annualPlanForm.value.title}"的分解计划`,
          tasks: allTasks,
          tasksText: allTasks.join('\n'),
          originalTasks: [{ title: `${monthName}重点工作`, description: '推进年度目标落实', priority: 'high', estimatedHours: 40 }],
          keyMetrics: '按时完成计划任务',
          year: currentYear
        }
      })
    }

    const editMonthlyPlan = (plan, index) => {
      editingMonthlyPlan.value = { ...plan }
      editingMonthlyIndex.value = index
      showEditMonthlyDialog.value = true
    }

    const saveMonthlyPlanEdit = () => {
      if (editingMonthlyIndex.value >= 0) {
        const updatedTasks = editingMonthlyPlan.value.tasksText.split('\n').filter(t => t.trim())
        editingMonthlyPlan.value.tasks = updatedTasks
        // Simple reconstruction of originalTasks for now
        editingMonthlyPlan.value.originalTasks = updatedTasks.map(t => ({
          title: t, description: '', priority: 'medium', estimatedHours: 0
        }))
        generatedMonthlyPlans.value[editingMonthlyIndex.value] = { ...editingMonthlyPlan.value }
        showEditMonthlyDialog.value = false
        ElMessage.success('修改已保存')
      }
    }

    const confirmMonthlyPlans = async () => {
      confirmingMonthly.value = true
      try {
        // 1. Create Annual Plan
        const annualResponse = await axios.post('/api/plans/annual', {
          year: annualPlanForm.value.year,
          title: annualPlanForm.value.title,
          description: annualPlanForm.value.description,
          objectives: annualPlanForm.value.objectives
        }, { headers: { Authorization: `Bearer ${authStore.token}` } })
        
        const annualPlanId = annualResponse.data.id

        // 2. Create Monthly Plans
        for (const plan of generatedMonthlyPlans.value) {
          await axios.post('/api/plans/monthly', {
            year: plan.year,
            month: plan.month,
            title: plan.title,
            description: plan.description,
            objectives: plan.keyMetrics,
            status: 'pending',
            annual_plan_id: annualPlanId
          }, { headers: { Authorization: `Bearer ${authStore.token}` } })
        }
        
        ElMessage.success('所有计划创建成功')
        workflowStep.value = 2
        await checkAnnualPlan()
      } catch (error) {
        ElMessage.error('创建失败，请重试')
      } finally {
        confirmingMonthly.value = false
      }
    }

    const handleWorkflowComplete = () => {
      showGuidedWorkflow.value = false
      activeTab.value = 'overview'
    }

    const deletePlan = async (plan) => {
      try {
        await ElMessageBox.confirm('确定要删除该年度计划吗？相关的月度计划也会被删除。', '警告', { type: 'warning' })
        await axios.delete(`/api/plans/annual/${plan.id}`, {
          headers: { Authorization: `Bearer ${authStore.token}` }
        })
        ElMessage.success('删除成功')
        checkAnnualPlan()
      } catch (e) {
        // cancel
      }
    }

    const viewPlanDetails = (plan) => {
      // Simple view for now, switch to annual tab
      activeTab.value = 'annual'
    }

    const getStatusType = (status) => {
      return { pending: 'info', in_progress: 'warning', completed: 'success' }[status] || 'info'
    }
    
    const getStatusText = (status) => {
      return { pending: '待开始', in_progress: '进行中', completed: '已完成' }[status] || status
    }

    // AI状态测试
    const testAIStatus = async () => {
      testingAI.value = true
      aiStatus.value = null
      aiStatusMessage.value = '正在测试...'
      aiStatusDetails.value = ''

      try {
        const response = await axios.get('/api/ai-suggestions/test-ai-status', {
          headers: { Authorization: `Bearer ${authStore.token}` }
        })

        if (response.data.available) {
          aiStatus.value = 'available'
          aiStatusMessage.value = response.data.message || 'AI服务正常'
          aiStatusDetails.value = response.data.details?.responseTime 
            ? `响应时间: ${response.data.details.responseTime}` 
            : ''
          
          ElMessage.success({
            message: `✅ ${aiStatusMessage.value}`,
            duration: 3000
          })
        } else {
          aiStatus.value = 'unavailable'
          aiStatusMessage.value = response.data.error || 'AI服务不可用'
          aiStatusDetails.value = response.data.details || ''
          
          ElMessage.error({
            message: `❌ ${aiStatusMessage.value}\n${aiStatusDetails.value}`,
            duration: 5000,
            dangerouslyUseHTMLString: false
          })
        }
      } catch (error) {
        aiStatus.value = 'unavailable'
        aiStatusMessage.value = 'AI服务连接失败'
        aiStatusDetails.value = error.message
        
        ElMessage.error({
          message: `❌ ${aiStatusMessage.value}`,
          duration: 5000
        })
      } finally {
        testingAI.value = false
      }
    }

    const fetchStats = async () => {
      try {
        const [annualRes, monthlyRes, weeklyRes] = await Promise.all([
          axios.get('/api/plans/annual', { headers: { Authorization: `Bearer ${authStore.token}` } }),
          axios.get('/api/plans/monthly', { headers: { Authorization: `Bearer ${authStore.token}` } }),
          axios.get('/api/plans/weekly', { headers: { Authorization: `Bearer ${authStore.token}` } })
        ])
        
        annualPlansCount.value = annualRes.data.length
        monthlyPlansCount.value = monthlyRes.data.length
        weeklyPlansCount.value = weeklyRes.data.length
        
        // 简单的待办计算：状态为 pending 的周计划
        pendingReportsCount.value = weeklyRes.data.filter(p => p.status === 'pending').length
        
        // 更新 existingAnnualPlans
        hasAnnualPlan.value = annualRes.data.length > 0
        existingAnnualPlans.value = annualRes.data
        
      } catch (error) {
        console.error('获取统计数据失败:', error)
      }
    }

    onMounted(() => {
      fetchStats()
    })

    return {
      user, activeTab, handleMenuSelect, handleLogout, getPageTitle,
      showPasswordDialog,
      showGuidedWorkflow, workflowStep, startNewAnnualPlan,
      annualPlanForm, annualRules, annualFormRef,
      generatingMonthly, generateMonthlyPlans,
      generatedMonthlyPlans,
      editMonthlyPlan, editingMonthlyPlan, showEditMonthlyDialog, saveMonthlyPlanEdit,
      confirmingMonthly, confirmMonthlyPlans, handleWorkflowComplete,
      existingAnnualPlans, annualPlansCount, monthlyPlansCount, weeklyPlansCount, pendingReportsCount,
      deletePlan, viewPlanDetails, getStatusType, getStatusText,
      // AI Status
      testingAI, aiStatus, aiStatusType, aiStatusIcon, aiStatusTooltip, testAIStatus
    }
  }
}
</script>

<style scoped>
.dashboard-container {
  height: 100vh;
  background-color: #f3f4f6;
}

.layout-container {
  height: 100%;
}

/* Sidebar */
.app-sidebar {
  background: white;
  border-right: 1px solid var(--border-color);
  display: flex;
  flex-direction: column;
}

.sidebar-header {
  height: 64px;
  display: flex;
  align-items: center;
  padding: 0 24px;
  border-bottom: 1px solid var(--border-color);
}

.logo-icon {
  width: 32px;
  height: 32px;
  background: var(--primary-color);
  border-radius: 8px;
  display: flex;
  align-items: center;
  justify-content: center;
  color: white;
  margin-right: 12px;
}

.app-name {
  font-weight: 700;
  font-size: 1.1rem;
  color: var(--text-main);
}

.sidebar-menu {
  border-right: none;
  padding: 16px 0;
  flex: 1;
}

.sidebar-footer {
  padding: 16px;
  border-top: 1px solid var(--border-color);
}

.user-profile {
  display: flex;
  align-items: center;
  padding: 8px;
  background: #f9fafb;
  border-radius: 8px;
}

.user-avatar {
  background: var(--primary-light);
  color: var(--primary-color);
  font-weight: 600;
}

.user-info {
  margin-left: 12px;
  flex: 1;
  display: flex;
  flex-direction: column;
}

.username {
  font-size: 0.9rem;
  font-weight: 600;
  color: var(--text-main);
}

.role {
  font-size: 0.75rem;
  color: var(--text-secondary);
}

.logout-btn {
  color: var(--text-secondary);
}

.logout-btn:hover {
  color: var(--danger-color);
}

/* Main Content */
.app-header {
  background: white;
  height: 64px;
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 0 32px;
  border-bottom: 1px solid var(--border-color);
}

.page-title {
  font-size: 1.25rem;
  font-weight: 600;
  color: var(--text-main);
}

.app-main {
  padding: 24px 32px;
  overflow-y: auto;
}

/* Overview Stats */
.stats-row {
  display: grid;
  grid-template-columns: repeat(4, 1fr);
  gap: 24px;
  margin-bottom: 32px;
}

.stat-card :deep(.el-card__body) {
  display: flex;
  align-items: center;
  padding: 20px;
}

.stat-icon {
  width: 48px;
  height: 48px;
  border-radius: 12px;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 24px;
  margin-right: 16px;
  color: white;
}

.bg-blue { background: #3b82f6; }
.bg-green { background: #10b981; }
.bg-purple { background: #8b5cf6; }
.bg-orange { background: #f59e0b; }

.stat-info {
  display: flex;
  flex-direction: column;
}

.stat-info .label {
  font-size: 0.875rem;
  color: var(--text-secondary);
}

.stat-info .value {
  font-size: 1.5rem;
  font-weight: 700;
  color: var(--text-main);
}

/* Workflow Overlay */
.workflow-overlay {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: rgba(0,0,0,0.5);
  z-index: 2000;
  display: flex;
  align-items: center;
  justify-content: center;
  backdrop-filter: blur(4px);
}

.workflow-container {
  background: white;
  width: 900px;
  max-width: 95vw;
  height: 85vh;
  border-radius: 16px;
  display: flex;
  flex-direction: column;
  box-shadow: var(--shadow-lg);
  overflow: hidden;
}

.workflow-header {
  padding: 24px 32px;
  border-bottom: 1px solid var(--border-color);
  display: flex;
  justify-content: space-between;
  align-items: flex-start;
}

.workflow-header h2 {
  font-size: 1.5rem;
  margin-bottom: 4px;
}

.workflow-header p {
  color: var(--text-secondary);
}

.workflow-steps {
  padding: 32px 64px;
  background: #f9fafb;
}

.workflow-content {
  flex: 1;
  overflow-y: auto;
  padding: 32px;
}

.step-content {
  max-width: 800px;
  margin: 0 auto;
}

.step-footer {
  margin-top: 40px;
  display: flex;
  justify-content: flex-end;
  gap: 16px;
  padding-top: 24px;
  border-top: 1px solid var(--border-color);
}

.monthly-grid-scroll {
  max-height: 400px;
  overflow-y: auto;
  padding: 4px;
}

.monthly-plans-grid {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(250px, 1fr));
  gap: 20px;
}

.monthly-preview-card {
  border: 1px solid var(--border-color);
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.month-badge {
  background: var(--primary-light);
  color: var(--primary-color);
  padding: 2px 8px;
  border-radius: 4px;
  font-size: 0.8rem;
  font-weight: 600;
}

.month-title {
  font-weight: 600;
  font-size: 0.9rem;
}

.card-body .desc {
  font-size: 0.85rem;
  color: var(--text-secondary);
  margin-bottom: 12px;
  display: -webkit-box;
  -webkit-line-clamp: 2;
  -webkit-box-orient: vertical;
  overflow: hidden;
}

.task-tag {
  margin-right: 4px;
  margin-bottom: 4px;
  max-width: 100%;
  overflow: hidden;
  text-overflow: ellipsis;
}

.centered {
  display: flex;
  justify-content: center;
  align-items: center;
  height: 100%;
}

/* Transitions */
.fade-enter-active, .fade-leave-active {
  transition: opacity 0.3s ease;
}
.fade-enter-from, .fade-leave-to {
  opacity: 0;
}
</style>
